﻿using AiMoInGH.Connector;
using AiMoWindows.GHAiMo;

namespace AiMoInGH.Pipeline
{
    /// <summary>
    /// 用来和AiMoWindows之间传递信息，
    /// </summary>
    class GHExecutorInfo
    {
        readonly ScriptRunner owner;
        // can be null 如果读取格式失败
        public GHScriptSource CurrentScript { get; private set; }
        string m_AssemblyPath = "";
        bool m_LangInCN = false;
        public GHExecutorInfo(ScriptRunner owner)
        {
            this.owner = owner;
            CurrentScript = owner.CurrentScript;
        }
        public void SendFirstScriptToAimoWindow(string pipeName)
        {
            if (CurrentScript.NotEmpty)
            {
                string scriptFileToGH = GHScriptIO.GetFileNameFromPipeName(pipeName);
                GHScriptIO.WriteToCache(CurrentScript.Usings, CurrentScript.Mains, CurrentScript.OtherFuncs,
                    CurrentScript.OtherClass, CurrentScript.ExternalAssembliesPaths, CurrentScript.ParamInfos, scriptFileToGH, CurrentScript.HasPublicCustomizedClasses);
            }
        }
        public void SetInfo(string[] paths, bool inCN)
        {
            if (paths.Length > 0)
            {
                m_AssemblyPath = paths[0];
            }
            m_LangInCN = inCN;
            CurrentScript = LoadGH_AiMoScriptsIO(m_AssemblyPath);
        }
        public bool Run()
        {
            if (CurrentScript != null && m_AssemblyPath != null)
            {
                bool re = owner.OnAiMoEditWindowRun(m_AssemblyPath, CurrentScript, out string error);
                RunCommandError = error;
                return re;
            }
            RunCommandError = "Debug: Script or AssemblyPath is Invalid";
            return false;
        }
        public string RunCommandError { get; set; } = "";

        GHScriptSource LoadGH_AiMoScriptsIO(string dllPath)
        {
            if (!GHScriptIO.ReadFromCache(GHScriptIO.GetSameScriptPath(dllPath), out string[] usings, out string[] mains, out string[] funcs, out string[] classes, out string[] externalReferences, out GH_ParamSyntaxNodeInfo[] paramInfos, out bool hasPublicCustomizedClasses)) return null;
            return new GHScriptSource(usings, mains, funcs, classes, externalReferences, paramInfos, hasPublicCustomizedClasses);
        }
    }
}
